package com.auerdi.dialog;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auerdi.AnimationUtils.AnimationUtils;
import com.auerdi.R;
import com.auerdi.dialog.flowlayout.FlowLayoutManager;
import com.auerdi.dialog.flowlayout.NestedRecyclerView;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.Buyinfor;
import com.example.egghttp.retrofit.beans.banner.Shuxing;
import com.example.egghttp.retrofit.beans.banner.Sku;
import com.example.egghttp.retrofit.beans.banner.SkuList;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.example.egghttp.retrofit.params.CollageDirectBuyRequest;
import com.squareup.picasso.Picasso;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by highsixty on 2018/3/15.
 * mail  gaolulin@sunmi.com
 */

public class CateGoryDialog extends AppCompatDialogFragment {


    private static Product mProduct;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.tt)
    View tt;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.ept)
    RelativeLayout ept;

    Unbinder unbinder;
    @BindView(R.id.close)
    TextView close;
    @BindView(R.id.plusleft)
    TextView plusleft;
    @BindView(R.id.minusright)
    TextView minusright;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.btn_ok)
    TextView btn_ok;


    private String sku_name1 = "-1";
    private String sku_name2 = "-1";
    private boolean isNotSet = true;
    private String mBuyType;


    public CateGoryDialog() {
        super();
    }

    public static CateGoryDialog newInstance(Product product, String buyType) {
        mProduct = product;

        CateGoryDialog fragment = new CateGoryDialog();
        Bundle args = new Bundle();
        args.putString("buyType", buyType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);


        Window window = getDialog().getWindow();
        WindowManager.LayoutParams windowParams = window.getAttributes();
//        windowParams.dimAmount = 0.0f;

        window.setAttributes(windowParams);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_category_layout, container, false);
        unbinder = ButterKnife.bind(this, view);
        AnimationUtils.slideToUp(view);


        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBuyType = (String) getArguments().get("buyType");
        L.d("hcia", "mBuyType:" + mBuyType);

        ept.setOnClickListener(v -> {
        });
        container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AnimationUtils.slideToDown(view, new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        dismiss();

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });


            }
        });
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                L.d("hcia", "mBuyType:" + mBuyType);


                CollageDirectBuyRequest dds = new CollageDirectBuyRequest(mProduct.getId(), sku_name1, sku_name2, num.getText() + "", "-1");
                RetrofitClient.getPDAClient().create(AdService.class).collageDirectBuy(dds)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(Schedulers.io())

                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BOb<Buyinfor>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BOb<Buyinfor> buyinforBOb) {
                                L.d("hcia", "buyinforBOb.getBody().getBuy_infos():" + buyinforBOb.getBody().getBuy_infos());

                                AnimationUtils.slideToDown(view, new Animation.AnimationListener() {
                                    @Override
                                    public void onAnimationStart(Animation animation) {

                                    }

                                    @Override
                                    public void onAnimationEnd(Animation animation) {

                                        dismiss();
//                                            EventBus.getDefault().post(ADOrderFragment.newInstance(mBuyType, buyinforBOb.getBody().getBuy_infos()));


                                    }

                                    @Override
                                    public void onAnimationRepeat(Animation animation) {

                                    }
                                });
                            }
                        });


            }
        });


        Picasso.get().load(mProduct.getLunboImg()).error(R.mipmap.logo).fit().placeholder(R.mipmap.logo).into(image);

        plusleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String ss = (Integer.parseInt(num.getText() + "") + 1) + "";
                num.setText(ss);
            }
        });
        minusright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ss = (Integer.parseInt(num.getText() + "") - 1) + "";
                if (ss.equals("0"))
                    return;

                num.setText(ss);
            }
        });


        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();


            }
        });


        RetrofitClient.getClient().create(AdService.class).collageSkuList(mProduct.getId())
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<SkuList>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(BOb<SkuList> skuListBOb) {


                        SkuList bo = skuListBOb.getBody();

                        List<Sku> skks = bo.getSkus();


                        if (skks.size() >= 1)
                            sku_name1 = skks.get(0).getShuxing().get(0).getName();
                        if (skks.size() >= 2)
                            sku_name2 = skks.get(1).getShuxing().get(0).getName();


                        recy.setLayoutManager(new GridLayoutManager(getActivity(), 1));
                        recy.addItemDecoration(getDecor());
                        recy.setAdapter(new CommonAdapter<Sku>(getActivity(), R.layout.item_flow, skks) {


                            @Override
                            public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
                                super.onBindViewHolder(holder, position, payloads);

                            }

                            @Override
                            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                                return super.onCreateViewHolder(parent, viewType);
                            }

                            @Override
                            protected void convert(ViewHolder holder, final Sku sku, final int outposition) {

                                holder.setText(R.id.flow_text, sku.getName());
                                NestedRecyclerView flowList = holder.getView(R.id.flowList);


                                if (isNotSet) {
                                    flowList.addItemDecoration(getDecor());
                                    isNotSet = false;
                                }
                                flowList.setLayoutManager(new FlowLayoutManager());
                                List<Shuxing> ssh = sku.getShuxing();
                                flowList.setAdapter(new CommonAdapter<Shuxing>(recy.getContext(), R.layout.item_flow_sub, ssh) {


                                    @Override
                                    protected void convert(ViewHolder hold, Shuxing shuxing, int position) {

                                        TextView ww = hold.getView(R.id.flow_text);
                                        hold.setText(R.id.flow_text, shuxing.getName());

                                        hold.getConvertView().setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                                if (outposition == 0) {
                                                    sku_name1 = shuxing.getName();

                                                }

                                                if (outposition == 1) {
                                                    sku_name2 = shuxing.getName();


                                                }
                                                Picasso.get().load(shuxing.getPic()).error(R.mipmap.logo).fit().placeholder(R.mipmap.logo).into(image);

                                                recy.getAdapter().notifyDataSetChanged();
                                            }
                                        });
                                        if (sku_name1 == shuxing.getName() || sku_name2 == shuxing.getName()) {

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                                ww.setBackground(hold.getConvertView().getContext().getResources().getDrawable(R.drawable.product_item_select_back));
                                                ww.setTextColor(hold.getConvertView().getContext().getResources().getColor(R.color.white));
                                            } else {
                                                ww.setBackgroundDrawable(hold.getConvertView().getContext().getResources().getDrawable(R.drawable.product_item_select_back));
                                                ww.setTextColor(hold.getConvertView().getContext().getResources().getColor(R.color.white));

                                            }
                                        } else {

                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                                ww.setBackground(hold.getConvertView().getContext().getResources().getDrawable(R.drawable.product_item_back));
                                                ww.setTextColor(hold.getConvertView().getContext().getResources().getColor(R.color.black));
                                            } else {
                                                ww.setBackgroundDrawable(hold.getConvertView().getContext().getResources().getDrawable(R.drawable.product_item_back));
                                                ww.setTextColor(hold.getConvertView().getContext().getResources().getColor(R.color.black));

                                            }
                                        }

                                    }


                                });


//
                            }
                        });


                    }
                });


    }

    @NonNull
    private RecyclerView.ItemDecoration getDecor() {
        return new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = AnimationUtils.dp2px(recy.getContext(), 10);
                outRect.left = AnimationUtils.dp2px(recy.getContext(), 10);
                outRect.right = AnimationUtils.dp2px(recy.getContext(), 10);
                outRect.bottom = AnimationUtils.dp2px(recy.getContext(), 10);
            }
        };
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {


        super.onDestroyView();
        unbinder.unbind();
    }
}
